package useraddress

import (
	"context"

	"mall/common/resultx"
	"mall/service/user/rpc/internal/svc"
	"mall/service/user/rpc/types/user"

	"github.com/zeromicro/go-zero/core/logx"
)

type DeleteUserAddressLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewDeleteUserAddressLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeleteUserAddressLogic {
	return &DeleteUserAddressLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *DeleteUserAddressLogic) DeleteUserAddress(in *user.RemoveIDsReq) (*user.BaseResp, error) {
	if in.VisitorId == nil || *in.VisitorId == 0 {
		return nil, resultx.StatusError(resultx.USER_ID_REQUIRED, "")
	}

	userId := *in.VisitorId
	tx, err := l.svcCtx.DB.BeginTx(l.ctx, nil)
	if err != nil {
		return nil, err
	}

	for _, id := range in.Ids {
		if id > 0 {
			err = l.svcCtx.UserAddress.SoftDelete(l.ctx, tx, id, userId)
			if err != nil {
				tx.Rollback()
				return nil, err
			}
		}
	}

	tx.Commit()

	return &user.BaseResp{}, nil
}
